<template>

    <el-form class="dx-input-baseform" ref="baseForm" :model="form" label-width="100px">
        <el-row v-for="(t,index) in groupFields" :key="index">    
            <el-col :span="f.span==2?24:12" v-for="(f,j) in t" :key="j">
                <slot v-if="$scopedSlots[f.columnName + (isEdit?'_edit_slot':'_add_slot')]?
                    $scopedSlots[f.columnName + (isEdit?'_edit_slot':'_add_slot')]:$slots[f.columnName + (isEdit?'_edit_slot':'_add_slot')]" 
                    :name="f.columnName + (isEdit?'_edit_slot':'_add_slot')" :data="{form:form,column:f,value:form[f.columnName]||''}"></slot>
                <el-form-item v-else :label="f.columnLabel" :prop="f.columnName" :rules="f.rules">
                    <!--数字类型检验-->
                    <dx-ctrl v-if="in_array(f.validators,['number','integer','float'])" 
                        :disabled="f.visible=='1'?true:false" :type="f.ctrlName" v-model.number="form[f.columnName]" :condition="cascadeCondiValue(form,f)"
                        @change="autocompleteValue($event,f,'',form)" :placeholder="f.placeholder?f.placeholder:''"
                        :code-type="f.codeType" :clearable="true"></dx-ctrl>
                    <dx-ctrl v-else :disabled="f.visible=='1'?true:false" :type="f.ctrlName"
                        @change="autocompleteValue($event,f,'',form)"
                        :multipleLimit="f.multiAmount" :placeholder="f.placeholder?f.placeholder:''"
                        v-model="form[f.columnName]" :condition="cascadeCondiValue(form,f)"
                        :code-type="f.codeType" :clearable="true"></dx-ctrl>
                    <slot :name="f.columnName + (isEdit?'_suffix_edit_slot':'_suffix_add_slot')" :data="{form:form,column:f,value:form[f.columnName]||''}"></slot>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <slot v-if="$scopedSlots['custom' + (isEdit?'_edit_slot':'_add_slot')] ? $scopedSlots['custom'+ (isEdit?'_edit_slot':'_add_slot')] : $slots['custom'+ (isEdit?'_edit_slot':'_add_slot')]" :name="'custom'+(isEdit?'_edit_slot':'_add_slot')" :data="form"></slot>
        </el-row>
        <el-row style="margin-bottom:20px;" v-if="slaveTables && slaveTables.length>0">
            <el-col :span="24">
            <el-tabs v-model="activeName" type="border-card">
                <el-tab-pane v-for="(table ,index) in slaveTables" :key="index">
                    <span slot="label"><dx-text :value="table.datamodelName" codeType='datamodel_codelist'></dx-text></span>

                    <el-table class="dx-input-slavetable" :row-style="rowStyle" :data="form[table.datamodelName]" border stripe style="width:100%;" :key="index">
                        <el-table-column fixed type="index" label="序号" align="center" width="50"></el-table-column>
                        <template v-for="(col ,_index) in table.fields">
                            <el-table-column :label="col.columnLabel" :key="_index" :width="col.width" align="center">
                                <template slot-scope="scope">
                                    <slot v-if="$scopedSlots[col.columnName + (isEdit?'_row_edit_slot':'_row_add_slot')]?
                                        $scopedSlots[col.columnName + (isEdit?'_row_edit_slot':'_row_add_slot')]:$slots[col.columnName + (isEdit?'_row_edit_slot':'_row_add_slot')]" 
                                        :name="col.columnName + (isEdit?'_row_edit_slot':'_row_add_slot')" :data="{row:scope.row,column:col,value:scope.row[col.columnName]||''}"></slot>

                                    <el-form-item v-else :inline-message="true" :prop="table.datamodelName + '.' + scope.$index + '.' + col.columnName" 
                                        :rules="col.rules" label-width="0px" style="margin: 0px;padding:0px;">
                                        <dx-ctrl v-if="in_array(col.validators,['number','integer','float'])" :disabled="col.visible=='1'?true:false" :type="col.ctrlName" 
                                            :condition="cascadeCondiValue(scope.row,col)" @change="autocompleteValue($event,col,table.datamodelName,scope.row)"
                                            v-model.number="scope.row[col.columnName]" 
                                            :placeholder="col.placeholder?col.placeholder:''"
                                            :code-type="col.codeType" :clearable="true"></dx-ctrl>
                                        <dx-ctrl v-else :disabled="col.visible=='1'?true:false" :type="col.ctrlName" v-model="scope.row[col.columnName]" 
                                            :condition="cascadeCondiValue(scope.row,col)" @change="autocompleteValue($event,col,table.datamodelName,scope.row)"
                                            :placeholder="col.placeholder?col.placeholder:''"
                                            :multipleLimit="col.multiAmount"
                                            :code-type="col.codeType" :clearable="true"></dx-ctrl>
                                        <slot :name="col.columnName + (isEdit?'_suffix_row_edit_slot':'_suffix_row_add_slot')" :data="{form:form,column:f,value:form[col.columnName]||''}"></slot>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                        </template>
                        <el-table-column label="操作" width="60" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="deleteRow(table,scope.$index,scope.row)"><i class="fa fa-remove"></i></el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-row type="flex" justify="center">
                        <el-button type="text" @click="addRow(table)" style="margin-bottom:10px;"><i class="el-icon-plus"></i> 增加一行</el-button>
                    </el-row>
                </el-tab-pane>
            </el-tabs>
            </el-col>
        </el-row>
        <el-row class="tx-c">
            <slot v-if="$scopedSlots['input_footer'+ (isEdit?'_edit_slot':'_add_slot')] ? $scopedSlots['input_footer'+ (isEdit?'_edit_slot':'_add_slot')] : $slots['input_footer'+ (isEdit?'_edit_slot':'_add_slot')]" :name="'input_footer'+(isEdit?'_edit_slot':'_add_slot')" :data="form"></slot>
            <template v-else>
                <el-button type="primary" :loading="isLoading" @click="doSubmit"><span v-if="!isEdit && submitVisible">{{saveText}}</span><span v-else>{{updateText}}</span></el-button>
                <el-button v-if="cancelVisible" @click="closeDialog">{{cancelText}}</el-button>
            </template>
        </el-row>
    </el-form>
</template>
<script>
import DxCtrl from '../dx-ctrl';
import DxText from '../dx-text'
import http from '../../../../assets/js/http.js'
import {unitProvider} from '../../../../assets/js/provider.js'
import toolkit from '../../../../assets/js/toolkit.js'
let validatorMsgs = {
    date : '输入必须是日期',
    string : '输入必须是字符',
    number : '输入必须是数字',
    boolean : '输入必须是布尔',
    integer : '输入必须是整数',
    float : '输入必须是小数',
    url : '输入必须是超链接',
    email : '输入必须是Email',
    array : '至少选择一项',
};
export default {
    components:{
        DxCtrl,
        DxText
    },
    props :{
        id : null,
        unitName : String,
        autoSubmit : {type:Boolean,default:true},
        defaultValue : {type:Object,default:()=>{}},
        saveText : {type:String,default:'立即创建'},
        updateText : {type:String,default:'保存'},
        cancelText : {type:String,default:'取消'},
        cancelVisible : {type:Boolean ,default: true},
        submitVisible : {type:Boolean ,default: true},
        //级联回调
        cascadeMethod : {type:Function,default:()=>true}
    },
    data(){
        return {
            activeName : '',
            routeName : '',
            dialogVisible : false,
            isloading : false,
            isCompileLoading : false,
            isEdit : false,
            formatters : {},
            form : {

            },
            keys : [],
            slaveKeys : {},
            fields : [],
            hiddenFields : {},
            slaveTables : [],
            groupFields : [],
            // rules : {},
            autocompleteInfo : {},
            cascadeInfo : [],
        };
    },
    computed : {
        //级联
        cascadeCondiValue(){
            return (obj,f)=>{
                let condition = {};
                if(this.cascadeMethod){
                    let executeCondition = this.cascadeMethod(obj,f,this.isEdit);
                    if(executeCondition && _.isPlainObject(executeCondition)){
                        return executeCondition;
                    }
                }
                if(f.cascadeField){
                    condition[f.cascadeField] = obj[f.cascadeField] || '';
                }
                return condition;
            }
        }
    },
    watch : {
        defaultValue(val){
            if(this.defaultValue){
                Object.assign(this.form , this.defaultValue);
            }
        }
    },
    methods:{
 
        //自动补全
        autocompleteValue(val,col,datamodel='',row){

            if(Array.isArray(val)) return;
            let tableType = col.tableType;
            let key = col.columnName; 
            if(tableType=='slave'){
                key = datamodel + "_" + key;
            }
            //级联重置
            // let cascadeColumName = this.cascadeInfo[key];
            // if(cascadeColumName && !val){
            //     console.log("-------->>>",row,'------------->>',cascadeColumName);
            //     row[cascadeColumName] = '';
            // }
            if(col.autocompleteField && col.columnName == col.autocompleteField){

                let autoFields = this.autocompleteInfo[key];
                if(!autoFields) return;
                autoFields.forEach(field=>{
                    if(val){
                        this.form[field] = val.other[field];
                    }else{
                        this.form[field] = '';
                    }
                    
                });
            }
        },
        //格式化
        formatter(row, column){
            let mValue = row[column.property];
            if(!mValue){
                return mValue;
            }
            let formatter = this.formatters[column.property];
            if(formatter){
                formatter = "this." + formatter;
                if (typeof (eval(formatter)) != "function") {
                    console.error('函数不存在!');
                    return "";
                }
                return eval(formatter + "(row, column);");
            }else{
                return mValue;
            }

        },
        rowStyle({ row, rowIndex}){
            if (row.J_MARK && row.J_MARK === 2) {
                return 'display:none'
            } else {
                return ''
            }
        },
        addRow(table){
            this.form[table.datamodelName].push({J_MARK:1});
        },
        deleteRow(table,index,row){
            let J_MARK = this.form[table.datamodelName][index].J_MARK;
            if(J_MARK==1){
                this.form[table.datamodelName].splice(index,1);
            }else{
                this.form[table.datamodelName][index].J_MARK = 2;
            }
        },
        closeDialog(){
            this.$emit('input-cancel',{form : this.form});
            this.$emit('update:dialogVisible', false);
        },
        validate(cb){

            if(cb){ 
               this.$refs.baseForm.validate(vaild=>{
                     cb(vaild);
                });
            }
        },
        doSubmit(){
           this.$refs.baseForm.validate(vaild=>{

                if(vaild){

                    if(this.autoSubmit){//是否自动提交

                        //数组使用逗号连接
                        // this.fields.forEach(field=>{

                        //     let value = this.form[field.columnName];
              
                        //     if(Array.isArray(value)){

                        //         this.form[field.columnName] = value.join(',');
                        //     }
                        // });
                        // this.slaveTables.forEach(table=>{
                        //     let datamodelName = table.datamodelName;
                        //     let slaveFields = table.fields;
                        //     slaveFields.forEach(field=>{
                        //         let value = this.form[field.columnName];
                        //         if(Array.isArray(value)){
                        //             this.form[datamodelName][field.columnName] = value.join(',');
                        //         }
                        //     });
                        // });

                        if(this.isEdit){
                            this.update();   
                        }else{
                            this.save();
                        }
                    }else{
                        this.$emit("input-submit",{form : this.form,flag : this.isEdit?'update':'save'});
                    } 
                }
            });
        },
        update(){
            this.isLoading = !this.isLoading
            console.log('this.form',this.form);
            this.apiPost('unit/ins/updateSave?unitName=' + this.unitName ,this.form).then(resp=>{
                this.isLoading = !this.isLoading
                if(resp.code==200){
                    _g.toastMsg('success', '操作成功！')
                    this.closeDialog();
                    this.$emit('dataChange','update'); 
                }else{
                    _g.toastMsg('error',resp.msg);
                }
            })

        },
        save(){
            this.isLoading = !this.isLoading
            console.log('this.form',this.form);
            this.apiPost('unit/ins/addSave?unitName=' + this.unitName ,this.form).then(resp=>{
                this.isLoading = !this.isLoading
                if(resp.code==200){
                    _g.toastMsg('success', '操作成功！')
                    this.closeDialog();
                    this.$emit('dataChange','save'); 
                }else{
                    _g.toastMsg('error',resp.msg);
                }
            })
        },
        initData(){
            unitProvider.loadUnitDefine(this.unitName).then(data=>{

          
                if(data){
                    if(data.tables){
                        
                        data.tables.forEach(t => {
           
                            if(t.tableType=='master'){
                                if(t.keys){
                                     this.keys = t.keys;
                                }
                                
                                if(this.isEdit){//编辑状态
                                    this.fields = t.editFields;
                                }else{
                                    this.fields = t.addFields;
                                }
                                //找到需要补全的簇字段
                                this.fields.forEach(item=>{
                                    this.$set(this.form,item.columnName,null);
                                    //查找格式器
                                    if(item.formatter){
                                        this.formatters[item.columnName] = item.formatter;
                                    }
                                    if(item.autocompleteField && item.autocompleteField==item.columnName){
                                        this.autocompleteInfo[item.autocompleteField] = [];
                                    }
                                   
                                });
                        
                                //找到需要补全的字段
                                this.fields.forEach(item=>{
                                    if(item.autocompleteField && item.autocompleteField!=item.columnName){
                                        this.autocompleteInfo[item.autocompleteField].push(item.columnName);
                                    }
                                    //级联字段注册
                                    if(item.cascadeField){
                                        this.cascadeInfo[item.cascadeField] = item.columnName;
                                    }
                                });

                                if(!this.isEdit){
                                    this.fields.forEach(item=>{
                                        if(item.defaultValue){
                                            this.form[item.columnName] = eval(item.defaultValue);
                                        }
                                    });
                                }

                                // console.log('autocompleteInfo',this.autocompleteInfo);

                                let hiddenMasterFields = [];
                                this.fields = this.fields.filter(f=>{
                                    if(f.visible === '2'){
                                        hiddenMasterFields.push(f);
                                    }
                                    return f.visible !== '2'

                                }); //过滤隐藏的列表
                                this.hiddenFields['master'] = hiddenMasterFields;//主表隐藏字段

                                let spanCol= (fields) => {
                                    let group = [] ,groups = [];
                                    for(let i=0;i < fields.length;i++){
                                        
                                        if(fields[i].span == 2){
                                            group = [];
                                            group.push(fields[i]);
                                            groups.push(group);
                                            group = [];
                                        }else{
                                            
                                            if(group.length == 2){
                                                group = [];
                                            }
                                            if(group.length==0){ 
                                                groups.push(group);
                                            }
                                            group.push(fields[i]);
                                        }
                                        
                                    }
                                    return groups;
                                }
                                // console.log(span(this.fields));

                                this.groupFields = spanCol(this.fields);

                                this.fields.forEach(item=>{


                                    // if(!item.rules[item.columnName]){
                                    //     item.rules[item.columnName] = [];
                                    // }

                                    if(!item.rules){
                                        item.rules = [];
                                    }
                                    let rule = {};
                                    if(item.validators){
                                        let validator = item.validators;
                                        rule = {required: true, message: `请输入${item.columnLabel}`};
                                        item.rules.push(rule);
                                        if(validator != 'notNull'){
                                            let message = validatorMsgs[validator] || '输入非法';
                                            rule = {type : validator, message : message};
                                            item.rules.push(rule);
                                        }
                                    }
                                    if(item.regex){
                                        rule = { pattern: new RegExp(item.regex,"g"), message: item.regexMsg || '非法输入！' };
                                        item.rules.push(rule);
                                    }
                                   
                                });
                                // console.log("rules",this.rules);
                                
                            }else{//子表

                                // this.form[t.datamodelName] = [];
                                
                                this.$set(this.form,t.datamodelName,[]);
                                let fields = [];
                                 if(t.keys){
                                     this.slaveKeys[t.datamodelName] = t.keys;
                                }
                                if(this.isEdit){//编辑状态
                                    fields = t.editFields;
                                }else{
                                    fields = t.addFields;
                                }

                                //找到需要补全的簇字段
                                fields.forEach(item=>{
                                    //查找格式器 子表
                                    if(item.formatter){
                                        this.formatters[t.datamodelName + "_" + item.columnName] = item.formatter;
                                    }
                                    if(item.autocompleteField && item.autocompleteField==item.columnName){
                                        this.autocompleteInfo[t.datamodelName + "_" +item.autocompleteField] = [];
                                    }
                                });
                                //找到需要补全的字段
                                fields.forEach(item=>{
                                    if(item.autocompleteField && item.autocompleteField!=item.columnName){
                                        this.autocompleteInfo[t.datamodelName + "_" + item.autocompleteField].push(item.columnName);
                                    }
                                     //级联字段注册
                                    if(item.cascadeField){
                                        this.cascadeInfo[t.datamodelName + "_" + item.cascadeField] = item.columnName;
                                    }

                                });
                                if(!this.isEdit){
                                    fields.forEach(item=>{
                                        if(item.defaultValue){
                                            this.form[t.datamodelName][item.columnName] = eval(item.defaultValue);
                                        }
                                    });
                                }
                                let hiddenSlaveFields = [];
                                fields = fields.filter(f=>{
                                    if(f.visible === '2'){

                                        hiddenSlaveFields.push(f);
                                    }
                                    return f.visible !== '2'
                                }); //过滤隐藏的列表
                                this.hiddenFields[t.datamodelName] = hiddenSlaveFields;

                                fields.forEach(item=>{

                                    if(!item.rules){
                                        item.rules = [];
                                    }

                                    let rule = {};
                                    if(item.validators){
                                        let validator = item.validators;
                                        rule = {required: true, message: `请输入${item.columnLabel}`};
                                        item.rules.push(rule);
                                        if(validator!='notNull'){
                                            let message = validatorMsgs[validator] || '输入非法';
                                            rule = {type : validator, message : message};
                                            item.rules.push(rule);
                                        } 
                                    }
                                    if(item.regex){
                                        rule = { pattern: new RegExp(item.regex,"g"), message: item.regexMsg || '非法输入！' };
                                        item.rules.push(rule);
                                    }
                                   
                                });

                                this.slaveTables.push({datamodelName:t.datamodelName,fields:fields});

                                // console.log(this.slaveTables);
                            }

                           
                        });
                         //
                        if(this.isEdit){

                            _g.openGlobalLoading();
                            this.apiGet("unit/ins/getEntry?unitName="+this.unitName+"&id="+this.id).then(result=>{
                                _g.closeGlobalLoading();
                                if(result.data){
                                    let data = result.data.master||[];
                                    if(!this.keys[0]){
                                        console.log('未配置主键，请配置');
                                        return;
                                    }
                                    // console.log('hiddenFields : ',this.hiddenFields);
                                    
                                    let needFields = this.fields.concat(this.hiddenFields['master']||[]) || [];
                                    

                                    needFields.forEach(item=>{
                                        this.form[item.columnName] = data[item.columnName];
                                    });
                                    for(let property in this.form){
                                        this.form[property] = this.formatter(this.form,{property});//格式数据
                                    }
                                    
                                    //主键
                                    this.form[this.keys[0]] = data[this.keys[0]];

                                    let slaves = result.data.slaves;
                                    if(slaves){
                                        for(let p in slaves){
                                            let curFields = this.slaveTables.filter(table=>{return table.datamodelName===p})[0].fields;
                                            if(!curFields){
                                                console.log('未配置子表字段，请配置');
                                                return;
                                            }
                                            
                                            let slaveData = slaves[p];
                                            let slaveKey = this.slaveKeys[p][0];
                                            if(!slaveKey){
                                                console.log('未配置子表主键，请配置');
                                                return;
                                            }
                                            if(this.form[p]){
                                                slaveData.forEach(item=>{

                                                    let mItem = {};
                                                    mItem.J_MARK = 3;

                                                    let needFields = this.fields.concat(this.hiddenFields[p]||[]) || [];
                                    
                                                    needFields.forEach(citem=>{
                                                        mItem[citem.columnName] = item[citem.columnName];
                                                    });

                                                    mItem[slaveKey] = item[slaveKey];//主键
                                                    for(let property in item){
                                                        mItem[property] = this.formatter(item,{property});//格式数据
                                                    }
                                                    // console.log('mItem',mItem);
                                                    this.form[p].push(mItem);
                                                }); 
                                            }
                                            
                                        }
                                    }
                                    this.$emit("data-loaded",result.data);
                                }
                            });
                        }else{
                            if(this.defaultValue){
                                Object.assign(this.form,this.defaultValue);
                            }
                        }
                        //
                    }

                }
            });
        }
    },
    created(){
        if(this.id){
            this.isEdit = true;
        }else{
            this.isEdit = false;
        
        }
        
        this.initData();
   
    },
    mounted(){

        this.routeName = this.$route.name;
        _g.closeGlobalLoading();
    },
    mixins:[http,toolkit]
}
</script>
